package com.xiaochong.bitong.api.filter;

import com.alibaba.fastjson.JSONObject;
import com.xiaochong.bitong.api.constant.HttpHeaderCons;
import com.xiaochong.bitong.api.constant.ReturnCode;
import com.xiaochong.bitong.api.userclient.JsonView;
import com.xiaochong.bitong.api.userclient.UserServiceClient;
import com.xiaochong.bitong.api.utils.RequestUtil;
import com.xiaochong.service.common.config.oss.OSSTool;
import com.xiaochong.service.common.config.redis.RedisServer;

import com.xiaochong.tir.common.data.mapper.BtUserMapper;
import com.xiaochong.tir.common.data.vo.BtUser;
import com.xiaochong.tir.common.data.vo.app.UserVo;
import com.xiaochong.tir.common.util.RedisKeyApp;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@WebFilter(urlPatterns="/*", initParams={@WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico")})
public class AuthFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RedisServer redisService;

    @Autowired
    private UserServiceClient userServiceClient;


    @Autowired
    private BtUserMapper btUserMapper;

    @Autowired
    OSSTool ossTool;


    @Override
    public void destroy() {
        logger.info("过滤器销毁");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest)request;

        logger.info(String.format("-----------------------bitong-api:%s-------------------------------",req.getServletPath()));

        //后缀为.bitong的链接 拦截， 其他放行
        if(RequestUtil.parseSuffix(req.getServletPath(), HttpHeaderCons.AUTH_URL)){
            Map<String, String> map = RequestUtil.getHeaderNames(req);
            String token = map.get(HttpHeaderCons.TOKEN);
            String version = map.get(HttpHeaderCons.VERSION);
            if(StringUtils.isNotBlank(token) && StringUtils.isNotBlank(version)){

                String userKey  = RedisKeyApp.USER_TOKEN+token;
                logger.info("访问用户Token："+userKey);
                if(!redisService.exists(userKey)) {
                    logger.info("访问用户Token不存在TIR缓存："+userKey);
                    //检查用户中心
                    String result = userServiceClient.checkUserToken(token);
                    logger.info("访问用户Token用户中心返回："+result);

                    JsonView jsonView =  JSONObject.parseObject(result ,JsonView.class);
                    if(ReturnCode.SUCCESS.endsWith(jsonView.getCode())){

                        UserVo userVo = JSONObject.parseObject(jsonView.getData().toString()).getObject("result"  ,UserVo.class);
                        BtUser btUser = new BtUser();
                        btUser.setEmail( userVo.getEmail() );
                        btUser.setMobile( userVo.getMobile() );
                        List<BtUser> btList = btUserMapper.selectByAccount( btUser );
                        if(btList != null && btList.size()>0){
                            btUser = btList.get(0);
                            if(StringUtils.isNotBlank(btUser.getImageUrl())){
                                String imgUrl=ossTool.getOSSUrl( btUser.getImageUrl() );
                                btUser.setImageUrl(imgUrl);
                            }
                            redisService.set(userKey , btUser,RedisKeyApp.ExpireTime.ONE_DAY*7);
                        }
                    }else{
                        response.setCharacterEncoding(HttpHeaderCons.CHARACTER_ENCODING);
                        response.setContentType(HttpHeaderCons.CONTENT_TYPE);
                        PrintWriter out=response.getWriter();
                        JsonView authError = new JsonView();
                        authError.setCode(ReturnCode.TOKEN_LOSE);
                        out.print(authError.toString());
                        out.flush();
                        out.close();
                        return ;
                    }
                }else{
                    redisService.expire(userKey,RedisKeyApp.ExpireTime.ONE_DAY*7);
                }
                chain.doFilter(request, response);
            }else {
                response.setCharacterEncoding(HttpHeaderCons.CHARACTER_ENCODING);
                response.setContentType(HttpHeaderCons.CONTENT_TYPE);
                PrintWriter out=response.getWriter();
                JsonView authError = new JsonView();
                authError.setCode(ReturnCode.TOKEN_LOSE);
                out.print(authError.toString());
                out.flush();
                out.close();
                return ;
            }
        }else{
            chain.doFilter(request, response);
        }

    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        logger.info("过滤器初始化");
    }


}
